﻿using System;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.API.Application.Models;
using Casamiel.API.Application.Services;
using Casamiel.Application;
using Casamiel.Common;
using MediatR;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;

namespace Casamiel.API.Application.Commands
{
    /// <summary>
    /// 
    /// </summary>
    public sealed class ThirdOrderPickupCommandHandler : IRequestHandler<ThirdOrderPickupCommand, Zmodel>
	{
		private readonly NLog.ILogger logger = LogManager.GetLogger("MeiTuanOrderService");
		private readonly IIcApiService _icApiService;
        private readonly IOrderService _order;
		 
		/// <summary>
		/// 
		/// </summary>
		/// <param name="iicApiService"></param>
        /// <param name="orderService"></param>
		public ThirdOrderPickupCommandHandler(IIcApiService iicApiService, IOrderService orderService)
		{
			_icApiService = iicApiService;
            _order = orderService;
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="request"></param>
		/// <param name="cancellationToken"></param>
		/// <returns></returns>
		public async Task<Zmodel> Handle(ThirdOrderPickupCommand request, CancellationToken cancellationToken)
		{
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            logger.Trace($"OrderPickup:{JsonConvert.SerializeObject(request)}");
			var entity = await _order.GetByOrderCodeAsync<ICasaMielSession>(request.OrderCode).ConfigureAwait(false);
			if (entity == null)
			{
				logger.Trace($"OrderPickup:订单不存在,{request.OrderCode}");
				return new Zmodel{ code = 9999, msg = "订单不存在" };
			}

			if (entity.OrderStatus == (int)OrderStatus.Completed)
			{
                logger.Trace($"OrderPickup:订单完成,{request.OrderCode}");
                return new Zmodel{ code = 8888, msg = "订单完成" };
			}

			IcorderpickupReq dto = new IcorderpickupReq()
			{
				Tradeno = entity.IcTradeNO
			};
            var re = await _icApiService.Icorderpickup(dto).ConfigureAwait(false);
			logger.Trace($"icorderpickup,result:{JsonConvert.SerializeObject(re)},req:{JsonConvert.SerializeObject(dto)}");
			if (re.code == 0 )
			{
				var jobject = JsonConvert.DeserializeObject<JObject>(re.content);
				var billno = jobject["billno"].ToString();
				entity.OrderStatus = (int)OrderStatus.Completed;
				await _order.UpdateOrderStatusAndResBillNOAsync<ICasaMielSession>(entity.OrderBaseId, entity.OrderStatus, billno).ConfigureAwait(false);
			}
            else if(re.code == 230)
            {
                entity.OrderStatus = (int)OrderStatus.Completed;
                await _order.UpdateOrderStatusAndResBillNOAsync<ICasaMielSession>(entity.OrderBaseId, entity.OrderStatus, entity.ResBillNo).ConfigureAwait(false);
            }
			return re;
		}
	}
}
